import React from "react";
import { connect } from "react-redux";
import { messages } from "share/common";
import { Modal, Button, Alert, message } from "antd";
import { openModal, removeContainer } from "components/method/openModal";
import Condition from "components/condition";
import InvoiceCheck from "./invoice-check-result";
import expenseReportService from "../../expense-report.service";
import "styles/expense-report/components/expense-check-result.scss";

const { If } = Condition;

class ExpenseCheckResult extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      confirmLoading: false,
      invoiceReasonRecords: [],
    };
  }

  formatCheckResult = () => {
    const { checkResult } = this.props;
    let warnList = [];
    let errorList = [];
    checkResult.map((item) => {
      if (item.type === 0) {
        warnList.push(item);
      } else {
        errorList.push(item);
      }
    });
    //强管控项需要在前面显示
    return errorList.concat(warnList);
  };

  //检查是否可以继续提交，强管控时不允许提交报销单
  checkSubmitAble = () => {
    const { checkResult } = this.props;
    return !(checkResult.filter((item) => item.type === 1).length > 0);
  };

  renderInfoMessage = () => {
    const { infoMessage } = this.props;
    if (typeof infoMessage === "string")
      return <Alert type="info" showIcon style={{ marginBottom: 10 }} message={infoMessage} />;
    else {
      return infoMessage;
    }
  };

  renderCheckResult = () => {
    const { invoiceExcessInfo } = this.props;
    return this.formatCheckResult().map((item, index) => {
      let messageList = [];
      if (item.message) {
        /**
         * 问：为啥分隔符要定为 1024bugfix 呢？
         * 答：因为用户可以自定义内容，为了与客户的提示信息不可能重复
         */
        messageList = item.message.split("1024bugfix"); //1024bugfix 多个message时的分隔符
      }
      // 有额外的超费用标准时，该标签需要在强弱管控信息中过滤掉
      if (invoiceExcessInfo.length && ["5001", "5002"].includes(item.externalPropertyName)) {
        return null;
      }
      return (
        <div className="check-result-item" key={index}>
          <If value={item.title}>
            <div className="check-result-item-title">
              <div className={`check-result-item-title-bg ${item.type === 0 ? "" : "error"}`} />
              <div className="check-result-item-title-info">{item.title}</div>
            </div>
          </If>
          <If value={item.subTitle}>
            <div className="result-sub-title">{item.subTitle}</div>
          </If>
          {messageList.map((messageItem) => (
            <div className="check-result-message">{messageItem}</div>
          ))}
        </div>
      );
    });
  };

  renderInvoiceExcess = () => {
    const { visible, invoiceExcessInfo, checkResult, entry } = this.props;
    // 超费用标准标签信息
    const invoiceResult = [];
    const invoiceErrorResult = checkResult.find((item) => item.externalPropertyName === "5002");
    const invoiceWarningResult = checkResult.find((item) => item.externalPropertyName === "5001");
    invoiceErrorResult && invoiceResult.push(invoiceErrorResult);
    invoiceWarningResult && invoiceResult.push(invoiceWarningResult);
    if (invoiceExcessInfo.length === 0) {
      return null;
    }
    return invoiceResult.map((invoiceTag) => (
      <div className="check-result-item">
        <div className="check-result-item-title">
          <div className={`check-result-item-title-bg ${invoiceTag.type === 1 ? "error" : ""}`} />
          <div className="check-result-item-title-info">
            {invoiceTag.title || messages("expense-1.key822") /*超费用标准*/}
          </div>
        </div>
        {visible && (
          <InvoiceCheck
            wrappedComponentRef={(node) => (this.invoiceCheckRef = node)}
            operation={entry === "approve" ? "2001" : "1001"}
            invoiceList={invoiceExcessInfo.filter((item) => item.type === invoiceTag.type)}
            isWeakCheck={this.checkSubmitAble()}
            getReasons={(invoiceReasonRecords) => this.setState({ invoiceReasonRecords })}
          />
        )}
      </div>
    ));
  };

  handleOk = () => {
    const { confirmSubmit, entry, expenseReportOID } = this.props;
    const { invoiceReasonRecords } = this.state;
    if (invoiceReasonRecords.length) {
      if (invoiceReasonRecords.some((item) => !item.record)) {
        this.invoiceCheckRef.props.form.validateFieldsAndScroll();
        // message.error(
        //   entry === "approve"
        //     ? messages("expense-1.key823") /*请输入审批意见*/
        //     : messages("expense-1.key824") /*请输入超标原因*/
        // );
        return;
      }
      invoiceReasonRecords.map((item) => {
        item.operation = entry === "approve" ? "2001" : "1001";
        item.expenseReportOID = expenseReportOID;
        return item;
      });
      this.setState({ confirmLoading: true });
      expenseReportService
        .saveInvoiceExcessReason(invoiceReasonRecords)
        .then(confirmSubmit)
        .finally(() => {
          this.setState({ confirmLoading: false });
        });
    } else {
      confirmSubmit();
    }
  };

  render() {
    const { visible, submitLoading, confirmText, cancelText, onCancel, infoMessage, invoiceExcessInfo } = this.props;
    const { confirmLoading } = this.state;
    return (
      <Modal
        title={messages("expense-1.key400") /*检查结果*/}
        visible={visible}
        onCancel={onCancel}
        wrapClassName="expense-check-result"
        bodyStyle={{ padding: 0, maxHeight: "80vh", overflow: "auto" }}
        width={invoiceExcessInfo.length > 0 ? 760 : 520}
        footer={[
          <Button className="back-btn" onClick={onCancel}>
            {cancelText || messages("common.back") /*返回*/}
          </Button>,
          <If value={this.checkSubmitAble() && confirmText}>
            <Button type="primary" onClick={this.handleOk} loading={confirmLoading || submitLoading}>
              {confirmText}
            </Button>
          </If>,
        ]}
      >
        <div className="expense-check-result-container">
          {infoMessage && this.renderInfoMessage()}
          {this.renderCheckResult()}
          {this.renderInvoiceExcess()}
        </div>
      </Modal>
    );
  }
}

ExpenseCheckResult.propTypes = {
  visible: React.PropTypes.bool,
  submitLoading: React.PropTypes.bool,
  checkResult: React.PropTypes.array,
  invoiceExcessInfo: React.PropTypes.array,
  entry: React.PropTypes.string, // 审批 approve
  confirmText: React.PropTypes.string,
  cancelText: React.PropTypes.string,
  infoMessage: React.PropTypes.any,
  expenseReportOID: React.PropTypes.string,
  confirmSubmit: React.PropTypes.func,
  onCancel: React.PropTypes.func,
};

ExpenseCheckResult.defaultProps = {
  visible: false,
  submitLoading: false,
  checkResult: [],
  invoiceExcessInfo: [],
  confirmText: "",
  cancelText: "",
  infoMessage: "",
  expenseReportOID: undefined,
  confirmSubmit: () => {},
  onCancel: () => {},
};

function mapStateToProps(state) {
  return {};
}

ExpenseCheckResult.open = function (props, env) {
  let container;
  const defaultProps = {
    checkResult: [],
    invoiceExcessInfo: [],
    confirmSubmit: () => {},
    onCancel: () => {},
  };
  props = Object.assign({}, defaultProps, props);
  const close = () => {
    removeContainer(container);
    container = null;
  };
  const targetProps = {
    ...props,
    visible: true,
    confirmSubmit: () => {
      props.confirmSubmit();
      close();
    },
    onCancel: () => {
      props.onCancel();
      close();
    },
  };
  container = openModal(ExpenseCheckResult, targetProps, env);
};

export default connect(mapStateToProps)(ExpenseCheckResult);
